<template>
  <div class="image-picker">
    <!-- 图片选择器和预览区域 -->
    <div v-if="!hidePreview" class="image-selector-preview">
      <!-- 如果有图片，显示预览 -->
      <div v-if="selectedImage" class="image-preview-container">
        <img :src="getImageUrl(selectedImage.url)" :alt="selectedImage.name" class="preview-image" />
        <el-button
          type="danger"
          :icon="Delete"
          circle
          size="small"
          @click="clearSelection"
          class="delete-btn"
        />
      </div>
      
      <!-- 选择按钮 -->
      <el-button
        type="primary"
        :icon="Picture"
        @click="openImageSelector"
        size="small"
        class="select-btn"
      >
        {{ selectedImage ? '更换图片' : '选择图片' }}
      </el-button>
    </div>
    <!-- 主对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="图片选择器"
      width="90%"
      :max-width="1400"
      :close-on-click-modal="false"
      append-to-body
      class="custom-dialog"
    >
      <!-- 标签页导航 -->
      <el-tabs v-model="activeTab" class="image-tabs" @tab-change="handleTabChange">
        <!-- 图片库标签页 -->
        <el-tab-pane label="图片库" name="gallery">
          <div class="gallery-container">
            <!-- 工具栏 -->
            <div class="toolbar">
              <div class="search-box">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索图片名称"
                  clearable
                  @input="handleSearch"
                  class="search-input"
                >
                  <template #prefix>
                    <el-icon class="search-icon"><Search /></el-icon>
                  </template>
                </el-input>
              </div>
              <div class="toolbar-actions">
                <el-button 
                  @click="refreshImages" 
                  class="refresh-btn"
                  size="default"
                >
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>
            </div>

            <!-- 图片网格 -->
            <div class="image-grid" v-loading="loading">
              <div
                v-for="image in filteredImages"
                :key="image.id"
                class="image-card"
                :class="{ selected: selectedImages.includes(image.id) }"
                @click="toggleSelect(image)"
              >
                <!-- 图片容器 -->
                <div class="image-wrapper">
                  <img 
                    :src="getImageUrl(image.url)" 
                    :alt="image.name" 
                    @error="handleImageError" 
                    :data-image="JSON.stringify(image)"
                    @load="handleImageLoad"
                    :class="{ loading: !image.loaded, error: image.error }"
                    class="preview-image"
                  />
                  
                  <!-- 加载状态 -->
                  <div v-if="!image.loaded && !image.error" class="image-skeleton">
                    <div class="skeleton-placeholder"></div>
                  </div>
                  
                  <!-- 选中状态标识 -->
                  <div v-if="selectedImages.includes(image.id)" class="selected-badge">
                    <el-icon><Check /></el-icon>
                  </div>
                </div>
                
                <!-- 图片信息和操作按钮 -->
                <div class="image-info-bar">
                  <!-- 图片信息 -->
                  <div class="image-info">
                    <div class="image-name" :title="image.name">{{ image.name }}</div>
                    <div class="image-meta">
                      <span class="image-size">{{ formatFileSize(image.size) }}</span>
                      <span class="image-date">{{ formatDate(image.createTime) }}</span>
                    </div>
                  </div>
                  
                  <!-- 操作按钮 - 修改为常驻显示在底部 -->
                  <div class="image-actions">
                    <el-tooltip content="预览">
                      <el-button
                        type="text"
                        size="small"
                        @click.stop="previewImage(image)"
                        class="action-btn preview-btn"
                      >
                        <el-icon><ZoomIn /></el-icon>
                      </el-button>
                    </el-tooltip>
                    <el-tooltip content="重命名">
                      <el-button
                        type="text"
                        size="small"
                        @click.stop="renameImage(image)"
                        class="action-btn rename-btn"
                      >
                        <el-icon><Edit /></el-icon>
                      </el-button>
                    </el-tooltip>
                    <el-tooltip content="删除">
                      <el-button
                        type="text"
                        size="small"
                        @click.stop="deleteImage(image)"
                        class="action-btn delete-btn"
                      >
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </el-tooltip>
                  </div>
                </div>
              </div>
              
              <!-- 空状态 -->
              <div v-if="filteredImages.length === 0 && !loading" class="empty-state">
                <el-empty 
                  description="暂无图片" 
                  class="empty-indicator"
                >
                  <template #image>
                    <el-icon class="empty-icon"><PictureRounded /></el-icon>
                  </template>
                </el-empty>
              </div>
            </div>

            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[12, 24, 36, 48]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                class="pagination"
              />
            </div>
          </div>
          <!-- 底部操作按钮 -->
        <div class="dialog-footer">
          <div class="selected-count">
            已选择 {{ selectedImages.length }} 张图片
          </div>
          <div class="action-buttons">
            <el-button 
              @click="dialogVisible = false"
              class="cancel-btn"
            >
              取消
            </el-button>
            <el-button 
              type="primary" 
              @click="confirmSelect"
              :disabled="selectedImages.length === 0"
              class="confirm-btn"
            >
              确定选择
            </el-button>
          </div>
        </div>
        </el-tab-pane>

        <!-- 上传图片标签页 -->
        <el-tab-pane label="上传图片" name="upload">
          <div class="upload-container">
            <el-upload
              :auto-upload="false"
              :on-change="handleFileChange"
              :show-file-list="false"
              accept="image/*"
              class="upload-area"
              multiple
              drag
            >
              <div class="upload-content">
                <el-icon class="upload-icon"><UploadFilled /></el-icon>
                <div class="upload-text">
                  <p class="upload-hint">支持 JPG、PNG、GIF 格式，单张不超过 5MB，单次最多上传 10 张</p>
                  <p class="upload-hint">上传完成后 => 返回图片库选择图片</p>
                </div>
              </div>
            </el-upload>
            
            <!-- 上传文件列表 - 已修改为与图片库一致的样式 -->
            <div v-if="uploadFileList.length" class="upload-list-container">
              <el-divider content-position="left">待上传文件</el-divider>
              <el-scrollbar max-height="300px">
                <!-- 使用与图片库相同的网格布局 -->
                <div class="image-grid">
                  <div
                    v-for="(file, index) in uploadFileList"
                    :key="index"
                    class="image-card"
                  >
                    <div class="image-wrapper">
                      <img
                        :src="file.url"
                        :alt="file.name"
                        class="preview-image"
                      />
                    </div>
                    
                    <!-- 图片信息和操作按钮 -->
                    <div class="image-info-bar">
                      <!-- 图片信息 -->
                      <div class="image-info">
                        <div class="image-name" :title="file.name">{{ file.name }}</div>
                        <div class="image-meta">
                          <span class="image-size">{{ formatFileSize(file.size) }}</span>
                        </div>
                      </div>
                      
                      <!-- 操作按钮 -->
                      <div class="image-actions">
                        <el-tooltip content="移除">
                          <el-button
                            type="text"
                            size="small"
                            @click.stop="handleRemoveFile(index)"
                            class="action-btn delete-btn"
                          >
                            <el-icon><Delete /></el-icon>
                          </el-button>
                        </el-tooltip>
                      </div>
                    </div>
                  </div>
                </div>
              </el-scrollbar>
              <div class="upload-actions">
                <el-button @click="clearFileList">清空列表</el-button>
                <el-button type="primary" @click="startUpload" :loading="uploading">
                  开始上传
                </el-button>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>      
    </el-dialog>

    <!-- 图片预览览对话框 -->
    <el-dialog 
      v-model="previewVisible" 
      title="图片预览" 
      width="90%"
      :max-width="1200"
      append-to-body
      class="preview-dialog"
    >
      <div class="preview-content">
        <img 
          :src="previewUrl" 
          :alt="previewName"
          class="full-preview"
          @load="previewLoaded"
        />
        <div v-if="previewLoading" class="preview-loading">
          <el-loading class="loading-spinner"></el-loading>
        </div>
      </div>
      <template #footer>
        <div class="preview-footer">
          <span class="preview-filename">{{ previewName }}</span>
          <el-button @click="previewVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 重命名对话框 -->
    <el-dialog 
      v-model="renameVisible" 
      title="重命名图片" 
      width="400px" 
      append-to-body
      class="rename-dialog"
    >
      <el-form 
        :model="renameForm" 
        :rules="renameRules" 
        ref="renameFormRef" 
        label-width="80px"
        class="rename-form"
      >
        <el-form-item label="名称" prop="name">
          <el-input 
            v-model="renameForm.name" 
            placeholder="请输入图片名称" 
            maxlength="50"
            class="name-input"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="renameVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmRename"
          class="confirm-rename-btn"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 脚本部分保持不变
import { ref, reactive, computed, onMounted, getCurrentInstance, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { 
  Search, Upload, Refresh, ZoomIn, Edit, Delete, 
  UploadFilled, Check, PictureRounded, Close, Picture 
} from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'
import request from '@/utils/request'

// 组件属性
const props = defineProps({
  multiple: {
    type: Boolean,
    default: false
  },
  maxCount: {
    type: Number,
    default: 10
  },
  hidePreview: {
    type: Boolean,
    default: false
  },
  initialImage: {
    type: Object,
    default: null
  }
})

// 获取当前实例
const { proxy } = getCurrentInstance()

// 事件
const emit = defineEmits(['select'])

// 状态变量
const dialogVisible = ref(false)
const activeTab = ref('gallery')
const loading = ref(false)
const images = ref([])
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(24)
const total = ref(0)
const selectedImages = ref([])
const previewVisible = ref(false)
const previewUrl = ref('')
const previewName = ref('')
const previewLoading = ref(false)
const renameVisible = ref(false)
const uploadLimit = ref(10) // 单次上传限制
const uploadFileList = ref([])
const uploading = ref(false) // 上传状态

// 当前选中的图片（用于预览）
const selectedImage = ref(props.initialImage)

// 重命名表单
const renameForm = reactive({
  id: '',
  name: ''
})

const renameRules = {
  name: [
    { required: true, message: '请输入图片名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ]
}

// 表单引用
const renameFormRef = ref(null)

// 上传相关配置
const uploadUrl = ref('/common/upload')  // 使用相对路径，让axios自动添加baseURL
const headers = ref({
  Authorization: "Bearer " + getToken()
})

// 过滤图片列表
const filteredImages = computed(() => {
  let result = [...images.value]

  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(img => 
      img.name.toLowerCase().includes(keyword)
    )
  }

  return result
})

// 打开选择器
function open() {
  dialogVisible.value = true
  activeTab.value = 'gallery'
  loadImages()
}

// 打开图片选择器（从预览区域）
function openImageSelector() {
  dialogVisible.value = true
  activeTab.value = 'gallery'
  loadImages()
}

// 清除选择
function clearSelection() {
  selectedImage.value = null
  emit('select', null)
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return ''
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

// 加载图片列表
function loadImages() {
  loading.value = true
  
  request({
    url: '/common/images/list',
    method: 'get',
    params: {
      dir: '/images',
      page: currentPage.value,
      pageSize: pageSize.value,
      search: searchKeyword.value
    }
  }).then(response => {
    if (response.code === 200) {
      images.value = response.data.images.map(img => ({
        ...img,
        loaded: false,
        error: false
      }))
      total.value = response.data.total
    }
    loading.value = false
  }).catch(error => {
    console.error("Error loading images:", error)
    loading.value = false
    ElMessage.error('加载图片失败')
  })
}

// 刷新图片列表
function refreshImages() {
  loadImages()
  ElMessage.success('已刷新图片列表')
}

// 处理标签切换
function handleTabChange(tabName) {
  if (tabName === 'gallery' && images.value.length === 0) {
    loadImages()
  }
}

// 搜索图片
function handleSearch() {
  currentPage.value = 1
  loadImages()
}

// 分页大小变更
function handleSizeChange(size) {
  pageSize.value = size
  currentPage.value = 1
  loadImages()
}

// 当前页变更
function handleCurrentChange(page) {
  currentPage.value = page
  loadImages()
}

// 获取图片URL
function getImageUrl(url) {
  if (!url) return ''
  if (url.startsWith('http')) return url
  if (url.startsWith('/profile')) return import.meta.env.VITE_APP_BASE_API + url
  return import.meta.env.VITE_APP_BASE_API + url
}

// 图片加载成功
function handleImageLoad(event) {
  const imageData = JSON.parse(event.target.dataset.image)
  const image = images.value.find(img => img.id === imageData.id)
  if (image) image.loaded = true
}

// 图片加载失败
function handleImageError(event) {
  event.target.onerror = null
  const imageData = JSON.parse(event.target.dataset.image)
  const image = images.value.find(img => img.id === imageData.id)
  if (image) {
    image.loaded = false
    image.error = true
  }
  event.target.src = ' wLjg5IDIgMnY1LjVDMTkgMTYuMTIgMTguMTEgMTcgMTcgMTdIM2MtMS4xMSAwLTIgMC44OC0yIDJ2MmgxNnYtMkg3LjVDNy41IDExLjA2IDguMDYgMTEgOC41IDExaDIuNUMxMS41IDExIDExIDEwLjQ2IDExIDkuNVY5ek0xMiAxNnYyaC0ydjJoMnptMCA0aC0ydjJoMnptNC04aC0ydjJoMnYtMnoiLz48L3N2Zz4='
  event.target.classList.add('error-img')
}

// 格式化文件大小
function formatFileSize(bytes) {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 切换图片选择状态
function toggleSelect(image) {
  if (!props.multiple) {
    selectedImages.value = [image.id]
  } else {
    const index = selectedImages.value.indexOf(image.id)
    if (index > -1) {
      selectedImages.value.splice(index, 1)
    } else {
      if (selectedImages.value.length >= props.maxCount) {
        ElMessage.warning(`最多只能选择${props.maxCount}张图片`)
        return
      }
      selectedImages.value.push(image.id)
    }
  }
}

// 预览图片
function previewImage(image) {
  previewUrl.value = getImageUrl(image.url)
  previewName.value = image.name
  previewVisible.value = true
  previewLoading.value = true
}

// 预览图加载完成
function previewLoaded() {
  previewLoading.value = false
}

// 重命名图片
function renameImage(image) {
  renameForm.id = image.id
  renameForm.name = image.name
  renameVisible.value = true
  // 重置表单验证
  nextTick(() => {
    renameFormRef.value?.resetFields()
  })
}

// 确认重命名
async function confirmRename() {
  const valid = await renameFormRef.value.validate()
  if (!valid) return

  request({
    url: `/common/images/rename`,
    method: 'post',
    data: {
      id: renameForm.id,
      name: renameForm.name
    }
  }).then(response => {
    if (response.code === 200) {
      const image = images.value.find(img => img.id === renameForm.id)
      if (image) image.name = renameForm.name
      renameVisible.value = false
      ElMessage.success('图片重命名成功')
    } else {
      ElMessage.error(response.msg || '重命名失败')
    }
  }).catch(() => {
    ElMessage.error('重命名失败')
  })
}

// 删除图片
function deleteImage(image) {
  ElMessageBox.confirm(
    `确定要删除图片"${image.name}"吗？`,
    '确认删除',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
      dangerMode: true
    }
  ).then(() => {
    request({
      url: `/common/images/delete/${image.id}`,
      method: 'delete'
    }).then(response => {
      if (response.code === 200) {
        const index = images.value.findIndex(img => img.id === image.id)
        if (index > -1) images.value.splice(index, 1)
        
        const selectedIndex = selectedImages.value.indexOf(image.id)
        if (selectedIndex > -1) selectedImages.value.splice(selectedIndex, 1)
        
        total.value--
        ElMessage.success('图片删除成功')
      } else {
        ElMessage.error(response.msg || '删除失败')
      }
    }).catch(() => {
      ElMessage.error('删除失败')
    })
  }).catch(() => {})
}

// 处理文件选择
function handleFileChange(file) {
  // 检查文件类型
  const isImage = file.raw.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('请上传图片格式的文件')
    return false
  }
  
  // 检查文件大小
  const isLt5M = file.raw.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB')
    return false
  }
  
  // 检查文件名
  if (file.raw.name.includes(',')) {
    ElMessage.error('文件名不能包含逗号')
    return false
  }
  
  // 检查上传数量限制
  if (uploadFileList.value.length >= uploadLimit.value) {
    ElMessage.error(`单次最多只能上传${uploadLimit.value}张图片`)
    return false
  }
  
  // 创建文件预览URL
  const url = URL.createObjectURL(file.raw)
  
  // 添加到上传列表
  uploadFileList.value.push({
    name: file.name,
    size: file.size,
    url: url,
    raw: file.raw
  })

  // 验证文件名
  if (file.name.includes(',')) {
    ElMessage.error('文件名不能包含逗号')
    handleRemoveFile(uploadFileList.value.length - 1)
    return false
  }

  return true
}

// 上传成功处理
function handleUploadSuccess(res, file) {
  // 更新上传列表状态
  const index = uploadFileList.value.findIndex(item => item.raw === file)
  if (index > -1) {
    uploadFileList.value.splice(index, 1)
  }

  if (res.code === 200) {
    // 添加新图片到列表
    const newImage = {
      id: Date.now().toString(),
      name: res.fileName || file.name,
      url: res.fileName,
      size: file.size,
      createTime: new Date().toISOString(),
      loaded: true,
      error: false
    }
    images.value.unshift(newImage)
    total.value++
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}

// 上传失败处理
function handleUploadError(err, file) {
  const index = uploadFileList.value.findIndex(item => item.raw === file)
  if (index > -1) {
    uploadFileList.value[index].error = true
  }
  ElMessage.error('上传失败，请重试')
}

// 超过上传数量限制
function handleExceed() {
  ElMessage.error('单次最多只能上传10张图片')
}

// 移除上传文件
function handleRemoveFile(index) {
  // 释放URL对象
  URL.revokeObjectURL(uploadFileList.value[index].url)
  uploadFileList.value.splice(index, 1)
}

// 清空上传列表
function clearFileList() {
  // 释放所有URL对象
  uploadFileList.value.forEach(file => {
    URL.revokeObjectURL(file.url)
  })
  uploadFileList.value = []
}

// 开始上传
function startUpload() {
  if (uploadFileList.value.length === 0) {
    ElMessage.warning('请选择要上传的图片')
    return
  }
  
  uploading.value = true
  
  // 创建FormData对象
  const formData = new FormData()
  uploadFileList.value.forEach(file => {
    formData.append('files', file.raw)
  })
  
  request({
    url: uploadUrl.value,
    method: 'post',
    headers: {
      ...headers.value,
      'Content-Type': 'multipart/form-data'
    },
    data: formData
  }).then(response => {
    uploading.value = false
    if (response.code === 200) {
      ElMessage.success('所有图片上传成功')
      // 清空上传列表
      clearFileList()
      // 重新加载图片列表
      loadImages()
    } else {
      ElMessage.error(response.msg || '上传失败')
    }
  }).catch(error => {
    uploading.value = false
    console.error('Upload error:', error)
    ElMessage.error('上传失败，请重试')
  })
}

// 确认选择
function confirmSelect() {
  if (selectedImages.value.length === 0) {
    ElMessage.warning('请至少选择一张图片')
    return
  }
  
  const selectedImageData = images.value.filter(img => selectedImages.value.includes(img.id))
  const image = props.multiple ? selectedImageData : selectedImageData[0]
  
  // 更新预览图片
  if (!props.multiple && image) {
    selectedImage.value = image
  }
  
  emit('select', image)
  dialogVisible.value = false
  selectedImages.value = []
}

// 暴露方法
defineExpose({
  open
})
</script>

<style lang="scss" scoped>
// 基础样式调整 - 增加窗口高度
.image-picker {
  --primary-color: #409eff;
  --success-color: #67c23a;
  --warning-color: #e6a23c;
  --danger-color: #f56c6c;
  --gray-color: #909399;
  --light-gray: #f5f7fa;
  --border-color: #e4e7ed;
  
  .image-selector-preview {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;
    
    .image-preview-container {
      position: relative;
      width: 80px;
      height: 80px;
      border-radius: 4px;
      overflow: hidden;
      border: 1px solid var(--border-color);
      
      .preview-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .delete-btn {
        position: absolute;
        top: -10px;
        right: -10px;
        z-index: 1;
      }
    }
    
    .select-btn {
      flex-shrink: 0;
    }
  }
  
  .custom-dialog {
    :deep(.el-dialog__body) {
      padding: 16px 24px;
      max-height: 85vh;
      overflow: hidden;
    }
  }
  
  .image-tabs {
    height: 75vh;
    display: flex;
    flex-direction: column;
    
    :deep(.el-tabs__nav) {
      padding: 0 10px;
    }
    
    :deep(.el-tabs__content) {
      flex: 1;
      overflow: hidden;
      padding: 10px 0 0;
    }
  }
}

// 图片库样式
.gallery-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 0 4px;
    
    .search-box {
      flex: 0 1 360px;
      
      .search-input {
        --el-input-height: 40px;
        
        :deep(.el-input__prefix) {
          left: 12px;
        }
        
        :deep(.el-input__inner) {
          padding-left: 40px;
          border-radius: 8px;
        }
      }
      
      .search-icon {
        color: var(--gray-color);
      }
    }
    
    .toolbar-actions {
      .refresh-btn {
        --el-button-height: 40px;
        border-radius: 8px;
      }
    }
  }
  
  .image-grid {
    flex: 1;
    overflow-y: auto;
    padding: 8px;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 12px;
    align-content: flex-start;
    max-width: 100%;
    
    // 滚动条美化
    &::-webkit-scrollbar {
      width: 6px;
      height: 6px;
    }
    
    &::-webkit-scrollbar-thumb {
      background-color: rgba(144, 147, 153, 0.3);
      border-radius: 3px;
    }
    
    .image-card {
      background: #fff;
      border-radius: 10px;
      overflow: hidden;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      transition: all 0.3s ease;
      cursor: pointer;
      position: relative;
      display: flex;
      flex-direction: column;
      
      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
      }
      
      &.selected {
        box-shadow: 0 0 0 2px var(--primary-color), 0 4px 12px rgba(64, 158, 255, 0.15);
        border: 2px solid var(--primary-color);
      }
      
      .image-wrapper {
        position: relative;
        width: 100%;
        aspect-ratio: 1 / 0.75;
        background-color: var(--light-gray);
        overflow: hidden;
        padding: 2px;
        box-sizing: border-box;
        
        .preview-image {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: transform 0.3s ease, opacity 0.3s ease;
          
          .image-card:hover & {
            transform: scale(1.05);
          }
        }
        
        .loading {
          opacity: 0.6;
        }
        
        .error-img {
          object-fit: contain;
          background-color: #fef0f0;
          padding: 20px;
        }
        
        .image-skeleton {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-color: var(--light-gray);
          display: flex;
          align-items: center;
          justify-content: center;
          
          .skeleton-placeholder {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background-color: #ddd;
            animation: pulse 1.5s infinite;
          }
        }
        
        .selected-badge {
          position: absolute;
          top: 8px;
          right: 8px;
          width: 28px;
          height: 28px;
          border-radius: 50%;
          /* 专门修改圆形背景颜色 */
          background-color: #f56c6c; /* 这里改为你需要的背景色（示例：红色） */            
          :deep(.el-icon) {
            color: white !important; /* √图标保持白色，与背景色形成对比 */
            font-weight: bold; /* 加粗文字（对部分图标有效） */
            font-size: 18px; /* 适当放大图标，视觉上更粗重 */
            transform: scale(1.1); /* 轻微缩放增强粗重感 */
          }
          color: rgb(250, 4, 4);
          display: flex;
          align-items: center;
          justify-content: center;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          z-index: 2;
        }
      }
      
      // 整合信息和操作按钮的底部区域
      .image-info-bar {
        padding: 10px;
        background-color: rgba(64, 158, 255, 0.05);
        border-top-color: rgba(64, 158, 255, 0.2);
        border-top: 1px solid var(--light-gray);
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-shrink: 0;
        
        .image-info {
          flex: 1;
          overflow: hidden;
          
          .image-name {
            font-size: 13px;
            font-weight: 500;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-bottom: 4px;
          }
          
          .image-meta {
            display: flex;
            justify-content: flex-start;
            gap: 8px;
            font-size: 11px;
            color: var(--gray-color);
            
            .image-size, .image-date {
              white-space: nowrap;
            }
          }
        }
        
        .image-actions {
          display: flex;
          gap: 8px;
          padding-left: 8px;
          
          .action-btn {
            padding: 0;
            margin: 0;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            border-radius: 4px;
            transition: all 0.2s;
            
            &:hover {
              background-color: var(--light-gray);
            }
            
            &.preview-btn {
              color: var(--primary-color);
            }
            
            &.rename-btn {
              color: var(--warning-color);
            }
            
            &.delete-btn {
              color: var(--danger-color);
            }
          }
        }
      }
    }
    
    .empty-state {
      grid-column: 1 / -1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 40px 0;
      color: var(--gray-color);
      
      .empty-indicator {
        --el-empty-description-font-size: 14px;
        
        .empty-icon {
          font-size: 48px;
          margin-bottom: 16px;
          color: #c0c4cc;
        }
      }
    }
  }
  
  .pagination-container {
    padding: 12px 0 8px;
    display: flex;
    justify-content: center;
    
    .pagination {
      :deep(.el-pagination__total) {
        margin-right: 16px;
      }
    }
  }
}

// 上传区域样式
.upload-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .upload-area {
    flex: none;
    border: 2px dashed var(--border-color);
    border-radius: 10px;
    padding: 40px 20px;
    text-align: center;
    transition: border-color 0.3s ease;
    
    &:hover {
      border-color: var(--primary-color);
    }
    
    .upload-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .upload-icon {
        font-size: 48px;
        color: var(--primary-color);
        margin-bottom: 16px;
      }
      
      .upload-text {
        .upload-hint {
          color: var(--gray-color);
          margin: 0;
          font-size: 14px;
        }
      }
    }
  }
  
  .upload-list-container {
    margin-top: 20px;
    
    .upload-actions {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      margin-top: 16px;
      padding: 0 8px;
    }
  }
}

// 底部按钮样式
.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  
  .selected-count {
    color: var(--gray-color);
    font-size: 14px;
  }
  
  .action-buttons {
    display: flex;
    gap: 10px;
  }
}

// 预览对话框样式
.preview-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    max-height: 80vh;
  }
  
  .preview-content {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    
    .full-preview {
      max-width: 100%;
      max-height: 80vh;
      object-fit: contain;
    }
    
    .preview-loading {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: rgba(255, 255, 255, 0.8);
    }
  }
  
  .preview-footer {
    display: flex;
    justify-content: space-between;
    width: 100%;
    
    .preview-filename {
      font-weight: 500;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      max-width: 60%;
    }
  }
}

// 重命名对话框样式
.rename-dialog {
  .rename-form {
    margin-top: 10px;
    
    .name-input {
      width: 100%;
    }
  }
}

// 动画效果
@keyframes pulse {
  0% {
    opacity: 0.6;
    transform: scale(1);
  }
  50% {
    opacity: 0.3;
    transform: scale(1.1);
  }
  100% {
    opacity: 0.6;
    transform: scale(1);
  }
}

// 响应式调整
@media (max-width: 1400px) {
  .image-grid {
    grid-template-columns: repeat(auto-fill, minmax(145px, 1fr));
  }
}

@media (max-width: 1200px) {
  .image-grid {
    grid-template-columns: repeat(auto-fill, minmax(135px, 1fr));
  }
}

@media (max-width: 992px) {
  .image-grid {
    grid-template-columns: repeat(auto-fill, minmax(125px, 1fr));
  }
}

@media (max-width: 768px) {
  .image-grid {
    grid-template-columns: repeat(auto-fill, minmax(115px, 1fr));
    gap: 10px;
  }
  
  .image-info-bar {
    padding: 6px 8px;
    
    .image-info {
      .image-name {
        font-size: 11px;
      }
      
      .image-meta {
        font-size: 9px;
      }
    }
    
    .image-actions {
      .action-btn {
        width: 20px;
        height: 20px;
        font-size: 12px;
      }
    }
  }
}

@media (max-width: 576px) {
  .image-grid {
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 8px;
  }
}
</style>